const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { materialStore } = require('../../../../../store/modules/material/materialStore');
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper } = pathImport;
const { logEvent } = require('../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../helpers/network_helper.js');

Page({
    data: {
        isAdmin: false,
        searchKey: '',
        isFilterOpen: false,
        cateOptions: [],
        cateIndex: 0,
        statusOptions: [],
        statusIndex: 0,
        sortType: 'createTime',
        sortVal: 'desc',
        isLoading: false,
        isAllLoaded: false
    },

    onLoad: async function(options) {
        // 创建store绑定
        this.storeBindings = createStoreBindings(this, {
            store: materialStore,
            fields: ['materialList', 'quickAccess', 'isFilterOpen'],
            actions: ['fetchMaterialList', 'searchMaterials', 'setCateFilter', 'setStatusFilter', 'setSorting',
                    'toggleExpandItem', 'addToQuickAccess', 'removeFromQuickAccess']
        });

        try {
            const res = await cloudHelper.callCloudData('user/role', {});
            
            if (res && res.data && res.data.isAdmin) {
                this.setData({
                    isAdmin: true
                });
            }
        } catch (err) {
            console.error('获取用户角色失败', err);
        }

        // 网络检测
        const net = await getNetworkStatus();
        if (!net.isConnected) {
            wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
        } else if (net.networkType === '2g') {
            wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
        }
        listenNetworkStatus((res) => {
            if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
            else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
        });
        logEvent('page_load', { page: 'material_index' });
    },

    onPullDownRefresh: function () {
        // 下拉刷新
        this.fetchMaterialList(true)
            .then(() => {
                wx.stopPullDownRefresh();
            });
    },
    
    onReachBottom: function () {
        // 上拉加载更多
        if (!this.data.isAllLoaded && !this.data.isLoading) {
            this.fetchMaterialList();
        }
    },
    
    // 搜索相关方法
    onInputChange: function(e) {
        this.setData({
            searchKey: e.detail.value
        });
    },
    
    onSearchConfirm: function() {
        this.searchMaterials(this.data.searchKey);
    },
    
    clearSearch: function() {
        this.setData({
            searchKey: ''
        });
        this.searchMaterials('');
    },
    
    // 筛选相关方法
    onFilterTap: function() {
        // 直接调用materialStore的方法而不是通过绑定
        materialStore.toggleFilter();
        // 同步状态到页面
        this.setData({
            isFilterOpen: materialStore.isFilterOpen
        });
    },
    
    // 上传资源相关方法
    onUploadTap: function() {
        // 直接跳转到上传页面，让用户在页面中选择类型
        wx.navigateTo({
            url: `/projects/oa/pages/material/pages/edit/material_edit?isUpload=true`,
            timeout: 10000, 
            fail: function(err) {
                // 处理超时错误
                if (err.errMsg && err.errMsg.includes("timeout")) {
                    wx.showToast({
                        title: "页面加载超时，请重试",
                        icon: "none"
                    });
                    return;
                }
                
                // 处理其他错误
                console.error("页面跳转失败:", err);
                wx.showToast({
                    title: "页面跳转失败",
                    icon: "none"
                });
            }
        });
    },
    
    onCateChange: function(e) {
        const index = e.detail.value;
        const cateId = this.data.cateOptions[index].value;
        
        this.setData({
            cateIndex: index
        });
        
        this.setCateFilter(cateId);
    },
    
    onStatusChange: function(e) {
        const index = e.detail.value;
        const status = this.data.statusOptions[index].value;
        
        this.setData({
            statusIndex: index
        });
        
        this.setStatusFilter(status);
    },
    
    onSortChange: function(e) {
        const type = e.currentTarget.dataset.type;
        let val = 'desc';
        
        if (this.data.sortType === type) {
            // 如果点击的是当前排序字段，切换排序方向
            val = this.data.sortVal === 'desc' ? 'asc' : 'desc';
        }
        
        this.setData({
            sortType: type,
            sortVal: val
        });
        
        this.setSorting(type, val);
    },
    
    // 资源项相关方法
    onItemTap: function(e) {
        const id = e.currentTarget.dataset.id;
        if (!id) return;
        
        // 跳转到资源详情页面
        wx.navigateTo({
            url: `/projects/oa/pages/material/pages/detail/material_detail?id=${id}`
        });
    },
    
    toggleExpand: function(e) {
        const id = e.currentTarget.dataset.id;
        if (!id) return;
        
        this.toggleExpandItem(id);
    },
    
    onItemLongPress: function(e) {
        const item = e.currentTarget.dataset.item;
        if (!item) return;
        
        const actions = ['添加到快速访问'];
        
        wx.showActionSheet({
            itemList: actions,
            success: res => {
                if (res.tapIndex === 0) {
                    // 添加到快速访问
                    const result = this.addToQuickAccess(item);
                    if (result) {
                        pageHelper.showSuccessToast('已添加到快速访问');
                    } else {
                        pageHelper.showNoneToast('该资源已在快速访问列表中');
                    }
                }
            }
        });
    },
    
    // 快速访问相关方法
    onQuickAccessTap: function(e) {
        const id = e.currentTarget.dataset.id;
        if (!id) return;
        
        // 跳转到资源详情页面
        wx.navigateTo({
            url: `/projects/oa/pages/material/pages/detail/material_detail?id=${id}`
        });
    },
    
    onQuickAccessLongPress: function(e) {
        const id = e.currentTarget.dataset.id;
        if (!id) return;
        
        wx.showActionSheet({
            itemList: ['从快速访问中移除'],
            success: res => {
                if (res.tapIndex === 0) {
                    this.removeFromQuickAccess(id);
                    pageHelper.showSuccessToast('已从快速访问移除');
                }
            }
        });
    },
    
    // 依赖项点击
    onDependencyTap: function(e) {
        const id = e.currentTarget.dataset.id;
        if (!id) return;
        
        // 跳转到资源详情页面
        wx.navigateTo({
            url: `/projects/oa/pages/material/pages/detail/material_detail?id=${id}`
        });
    },

    onUnload: function() {
        // 清理Store绑定
        this.storeBindings.destroyStoreBindings();
    },

    switchTab: function(e) {
        let tab = e.currentTarget.dataset.tab;
        logEvent('switch_tab', { tab });
        this.setData({
            currentTab: tab
        });
    }
}); 